package com.socket.netty;

import com.socket.batch.collector.DataAnalysis;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;


/**
 * Created by kaddddd on 2017/7/4 0004.
 */
public class NettyClient {

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void connect(int port, String host) throws Exception {
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    byte[] bytes = DataAnalysis.hex2Bytes("5D");
                    ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, byteBuf));
                    ch.pipeline().addLast(new LoginClientHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect("localhost", 8085).sync(); // (5)
            //ChannelFuture f = b.connect("58.49.52.110", 8085).sync(); // (5)
            // Wait until the connection is closed.
//            if (f.awaitUninterruptibly(5000)) {
//                if (f.channel().isActive()) {
//                    System.out.println("开始发送消息");
//                    ByteBuf firstMessage;
//                    String s = "0x5B0000005A020000000F120000BC614E0100010000000000C3F6423030303030000000000000000000000000000112020000002400130607E10F0A220686805F023B4585003E0046000016C600530033000000130000000066305D";
//                    byte[] req = s.getBytes();
//                    firstMessage = Unpooled.buffer(req.length);
//                    firstMessage.writeBytes(req);
//                    for (int i = 0; i < 100; i++) {
//                        f.channel().writeAndFlush(firstMessage);
//                    }
//                    System.out.println("发送消息完毕");
//                }
//            }
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{
        new NettyClient().connect(8085, "localhost");
    }
}
